package com.eascs.ticket.schedule.controller;

import javax.inject.Inject;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eascs.common.assertion.util.AssertWarnUtils;
import com.eascs.common.util.ObjectUtil;
import com.eascs.common.util.StringUtil;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.ticket.common.entity.EntityUtil;
import com.eascs.ticket.common.form.OptionalIdForm;
import com.eascs.ticket.schedule.entity.ScheduleTicket;
import com.eascs.ticket.schedule.entity.ScheduleTicketUpdate;
import com.eascs.ticket.schedule.form.SaveScheduleTicketForm;
import com.eascs.ticket.schedule.service.ScheduleTicketService;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

@RestController
public class ScheduleTicketRestController extends BaseRestController {

	@Inject
	private ScheduleTicketService scheduleTicketService;

	@RequestMapping(value = "/schedule/rest/saveScheduleTicket")
	public BaseRestResult<String> saveScheduleTicket(SaveScheduleTicketForm saveScheduleTicketForm) {
		String id = saveScheduleTicketForm.getId();
		if (StringUtil.hasText(saveScheduleTicketForm.getId())) {
			User user = UserHolder.getUser();
			AssertWarnUtils.assertTrue(user.isSuperAdministrator() || user.getCode().equals(scheduleTicketService.getScheduleTicketById(saveScheduleTicketForm.getId()).getCreator()), "该记录只有创建人或者管理员才有权限变更");
			ScheduleTicketUpdate scheduleTicketUpdate = new ScheduleTicketUpdate();
			ObjectUtil.copySimpleProperties(saveScheduleTicketForm, scheduleTicketUpdate);
			EntityUtil.initUpdateEntity(scheduleTicketUpdate);
			scheduleTicketService.updateScheduleTicket(scheduleTicketUpdate);
		} else {
			ScheduleTicket scheduleTicket = new ScheduleTicket();
			ObjectUtil.copySimpleProperties(saveScheduleTicketForm, scheduleTicket);
			EntityUtil.initInsertEntity(scheduleTicket);
			ScheduleTicket scheduleTicketResult = scheduleTicketService.insertScheduleTicket(scheduleTicket);
			id = scheduleTicketResult.getId();
		}

		return BaseRestResult.redirect("/schedule/view/viewScheduleTicket?id=" + id);
	}

	@RequestMapping(value = "/schedule/rest/scheduleTicketEditView")
	public HtmlRestResult getScheduleTicketEditView(OptionalIdForm optionalIdForm) {
		if (StringUtil.hasText(optionalIdForm.getId())) {
			ViewContext.put("scheduleTicket", this.scheduleTicketService.getScheduleTicketById(optionalIdForm.getId()));
		}
		return HtmlRestResult.popHtmlFragment("/schedule/scheduleTicketEditView");
	}

}
